package com.mars.asyn;

import org.apache.commons.lang3.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;

import java.util.concurrent.Callable;

/**
 * 异步处理
 * @author MARS
 * @date 2018/7/18
 */
@RestController
public class AsyncController {

    @Autowired
    private  MockQueue mockQueue;

    @Autowired
    private DeferredResultHolder deferredResultHolder;

    private Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 同步处理请求方式
     *
     * @return
     * @throws Exception
     */
    @RequestMapping("/order/synchronize")
    public String orderSynchronize() throws Exception{
        logger.info("主线程开始");
        Thread.sleep(1000);
        logger.info("主线程返回");
        return "success";
    }

    /**
     *
     * 异步处理请求方式一
     *
     */
    @RequestMapping("/order/callable")
    public Callable<String> orderCallable() throws Exception{
        logger.info("主线程开始");
        // 异步处理方法
        Callable<String> result = new Callable<String>() {
            @Override
            public String call() throws Exception {
                logger.info("副线程开始");
                Thread.sleep(1000);
                logger.info("副线程结束返回");
                return "success";
            }
        };
        logger.info("主线程返回");
        return result;
    }

    /**
     *
     * 异步处理请求方式二
     *
     */
    @RequestMapping("/order/deferred")
    public DeferredResult<String> orderDeferred() throws Exception{
        logger.info("主线程开始");
        // 生成随机订单,8位随机数
        String orderNumber = RandomStringUtils.randomNumeric(8);
        mockQueue.setPlaceOrder(orderNumber);

        DeferredResult<String> result  = new DeferredResult<>();

        deferredResultHolder.getMap().put(orderNumber,result);
        logger.info("主线程返回");
        return result;
    }
}
